package com.example.pdfutils.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * 描述
 *
 * @author yuyong
 * @version 1.0
 * @date 2022-12-12
 */
@RestController
@RequestMapping("/pdf/utils")
@Slf4j
public class PdfController {

    @RequestMapping(value = "tpng", method = {RequestMethod.GET, RequestMethod.POST})
    BaseResult<List<String>> pdf2Png(@RequestParam("path") String path,
                                     @RequestParam(value = "dpi", defaultValue = "144", required = false) float dpi) {
        return BaseResult.success(pdf2png(path, dpi));
    }


    /**
     * 转换全部的pdf
     *
     * @param fileAddress 文件地址
     */
    public static List<String> pdf2png(String fileAddress, float dpi) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fileAddress);
        String[] split = file.getName().split("\\.");
        String name;
        if (split.length > 0) {
            name = split[0];
        } else {
            name = UUID.randomUUID().toString();
        }
        name = name + "_" + (int) dpi;
        List<String> result = new LinkedList<>();
        try (PDDocument doc = PDDocument.load(file)) {
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            PDPageTree pages = doc.getPages();
            PDPage pdPage = doc.getPages().get(0);

            for (int i = 0; i < pageCount; i++) {
                // Windows native DPI
                File pngFile = new File(file.getParent() + File.separator + name + "_" + (i + 1) + ".png");
                if (pngFile.exists()) {
                    pngFile.delete();
                }
                result.add(pngFile.getAbsolutePath());
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, "png", pngFile);
            }
        } catch (IOException e) {
            log.error("pdf to png error, file:{}, e:{}", (fileAddress), e.getMessage());
        }
        return result;
    }

}
